package cn.ffcs.contract.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import cn.ffcs.bpm.model.ProcTranRecord;
import cn.ffcs.bpm.model.ProcessConfigDetail;
import cn.ffcs.bpmpvc.model.BpmAppInfo;
import cn.ffcs.bpmpvc.services.AppBusinessReqService;
import cn.ffcs.bpmpvc.services.bean.ConfigBean;
import cn.ffcs.bpmpvc.svc.ProcessPvcService;
import cn.ffcs.bpmpvc.svc.TaskAssignBean;
import cn.ffcs.bpmpvc.svc.TaskService;
import cn.ffcs.bpmpvc.web.views.ProcessInstView;
import cn.ffcs.contract.dao.ContractRemindDao;
import cn.ffcs.contract.model.ContractBussout;
import cn.ffcs.contract.model.ContractRemind;
import cn.ffcs.contract.service.ContractRemindService;
import cn.ffcs.contract.web.view.ContractBussoutView;
import cn.ffcs.organ.model.Person;

public class ContractRemindServiceImpl implements ContractRemindService {
	private static final Logger logger = Logger.getLogger(ContractRemindServiceImpl.class);
	private ContractRemindDao contractRemindDao;
	private ProcessPvcService processPvcService;
	private AppBusinessReqService appBusinessReqService;
	private TaskService taskService;
	private ConfigBean configBean;

	private Person getStartPerson(String roleName) {
		Person startPerson = null;
		List<Person> personList = getProcessPvcService().getFlowPvcDao().findPersonByRoleName(roleName);
		if (personList != null && personList.size() > 0) {
			startPerson = personList.get(0);
		}
		return startPerson;
	}

	private String[] getDeptLeaderPerson() {
		String deptRoleName = "合同管理部门经理角色";
		Person deptManager = null;
		String userIdArr[] = null;
		List<Person> deptPersonList = getProcessPvcService().getFlowPvcDao().findPersonByRoleName(deptRoleName);
		if (deptPersonList != null && deptPersonList.size() > 0) {
			deptManager = deptPersonList.get(0);
			String deptMangerId = deptManager.getId().toString();
			userIdArr = new String[] { deptMangerId };
		}
		return userIdArr;
	}

	public void runCondRemind() {
		// TODO Auto-generated method stub
		logger.info("合同约束到期提醒start>>>>");
		List<ContractRemind> list = contractRemindDao.findCurrentList();
		if (list != null && list.size() > 0) {
			String processConfigId = getAppBusinessReqService().getFlowContractRemindProcessId();
			ProcessConfigDetail startNode = getProcessPvcService().getFlowPvcDao().getProcessStartNode(processConfigId);
			String roleName = startNode.getSecRole();
			if (StringUtils.isNotBlank(roleName)) {
				List<Person> personList = getProcessPvcService().getFlowPvcDao().findPersonByRoleName(roleName);
				
				if (personList != null && personList.size() > 0) {
					Person startPerson = personList.get(0);
					for (ContractRemind contractRemind : list) {
						ProcessInstView processInstView = getProcessPvcService().startProcessInst(processConfigId, startPerson);
						
						String procinstId = processInstView.getProcessStatus().getProcinstId().toString();
						String id = contractRemind.getId().toString();
						getContractRemindDao().updateRemind(id, "2", procinstId);
						//
						BpmAppInfo appInfo = new BpmAppInfo();
						appInfo.setAppId(contractRemind.getContractId());
						appInfo.setProcinstId(procinstId);
						appInfo.setAppTitle(contractRemind.getCondNote());
						appInfo.setAppType("01");
						appInfo.setOpTime(new Date());
						getContractRemindDao().merge(appInfo);
					}
				}
			}
		}
		logger.info("合同约束到期提醒end>>>>");
	}

	// 对于合同特殊约束款，周期提醒功能
	public void runCondRepeatRemind() {
		logger.info("合同特殊约束条件提醒start>>>>");
		List<ContractRemind> list = contractRemindDao.findCurrentListNew();
		if (list != null && list.size() > 0) {
			logger.info("发起记录数："+list.size());
			Date currentDate=new Date();
			String processConfigId = getAppBusinessReqService().getFlowContractRemindProcessId();
			ProcessConfigDetail startNode = getProcessPvcService().getFlowPvcDao().getProcessStartNode(processConfigId);
			String roleName = startNode.getSecRole();
			Person startPerson = getStartPerson(roleName);
			String startId=startPerson.getId().toString();
			//String userIdArr[] = getDeptLeaderPerson();
			if (startPerson != null) {
				for (ContractRemind contractRemind : list) {
					if("01".equals(contractRemind.getTimeType())&&StringUtils.isNotBlank(contractRemind.getProcinstId())){
						continue;
					}
					logger.info("合同记录ID："+contractRemind.getContractId());
					ProcessInstView processInstView = getProcessPvcService().startProcessInst(processConfigId, startPerson);
					// 传阅给经理
					/**
					if (userIdArr != null) {
						getTaskService().taskReadingToDo(processInstView.getProcTranRecord(), "传阅", userIdArr);
					}**/
					
					String procinstId = processInstView.getProcessStatus().getProcinstId().toString();
					BpmAppInfo appInfo=new BpmAppInfo();
					appInfo.setProcinstId(procinstId);
					appInfo.setAppTitle(contractRemind.getCondNote());
					appInfo.setAppType("01");
					appInfo.setAppId(contractRemind.getContractId());
					appInfo.setOpTime(new Date());
					appInfo.setStartUser(startId);
					getContractRemindDao().merge(appInfo);
					//更新下一个时间点
					if("01".equals(contractRemind.getTimeType())){
						contractRemind.setNextTime(null);
						contractRemind.setProcinstId(procinstId);
					}else{
						//计算下一次提醒的时间
						Calendar ca=Calendar.getInstance();
						ca.setTime(currentDate);
						ca.set(Calendar.DAY_OF_MONTH, contractRemind.getMonDay());
						ca.add(Calendar.MONTH, 1);
						
						ca.set(Calendar.HOUR_OF_DAY, 0);
						ca.set(Calendar.MINUTE, 0);
						ca.set(Calendar.SECOND, 0);
						ca.set(Calendar.MILLISECOND, 0);
						contractRemind.setNextTime(ca.getTime());
						if(contractRemind.getEndTime()!=null){
							if(contractRemind.getEndTime().before(ca.getTime())){
								contractRemind.setNextTime(null);
							}
						}
					}
					contractRemindDao.save(contractRemind);
				}
			}
		}
		logger.info("合同特殊约束条件end>>>>");
	}
	
	public void runCondRepeatRemindForBussOut() {
		logger.info("合同特殊约束条件提醒start>>>>");
		List<ContractRemind> list = contractRemindDao.findCurrentListNew();
		if (list != null && list.size() > 0) {
			logger.info("发起记录数："+list.size());
			Date currentDate=new Date();
			String processConfigId = getAppBusinessReqService().getFlowContractBussOutProcessId();
			ProcessConfigDetail startNode = getProcessPvcService().getFlowPvcDao().getProcessStartNode(processConfigId);
			String roleName = startNode.getSecRole();
			Person startPerson = getStartPerson(roleName);
			String startId=startPerson.getId().toString();
			if (startPerson != null) {
				for (ContractRemind contractRemind : list) {
					if("01".equals(contractRemind.getTimeType())&&StringUtils.isNotBlank(contractRemind.getProcinstId())){
						continue;
					}
					logger.info("合同记录ID："+contractRemind.getContractId());
					ProcessInstView processInstView = getProcessPvcService().startProcessInst(processConfigId, startPerson);
						
					String procinstId = processInstView.getProcessStatus().getProcinstId().toString();
					ContractBussout contractBussout=new ContractBussout();
					contractBussout.setUserId(startId);
					contractBussout.setReqCode(getAppBusinessReqService().getReqCode());		
					contractBussout.setApplyTime(new Date());
					contractBussout.setProcinstId(processInstView.getProcessStatus().getProcinstId().toString());
					contractBussout.setContractId(contractRemind.getContractId());
					getContractRemindDao().merge(contractBussout);
					//更新下一个时间点
					if("01".equals(contractRemind.getTimeType())){
						contractRemind.setNextTime(null);
						contractRemind.setProcinstId(procinstId);
					}else{
						//计算下一次提醒的时间
						Calendar ca=Calendar.getInstance();
						ca.setTime(currentDate);
						ca.set(Calendar.DAY_OF_MONTH, contractRemind.getMonDay());
						ca.add(Calendar.MONTH, 1);
						
						ca.set(Calendar.HOUR_OF_DAY, 0);
						ca.set(Calendar.MINUTE, 0);
						ca.set(Calendar.SECOND, 0);
						ca.set(Calendar.MILLISECOND, 0);
						contractRemind.setNextTime(ca.getTime());
						if(contractRemind.getEndTime()!=null){
							if(contractRemind.getEndTime().before(ca.getTime())){
								contractRemind.setNextTime(null);
							}
						}
					}
					contractRemindDao.save(contractRemind);
				}
			}
		}
		logger.info("合同特殊约束条件end>>>>");
	}
	// 对于合同三个月到期的提醒
	public void runContractDue2Month() {
		logger.info("合同3个月到期前提醒start>>>>");
		List<BpmAppInfo> list = contractRemindDao.findDue3MonthContractList();
		if (list != null && list.size() > 0) {
			String processConfigId = getAppBusinessReqService().getFlowContractRemindProcessId();
			ProcessConfigDetail startNode = getProcessPvcService().getFlowPvcDao().getProcessStartNode(processConfigId);
			String roleName = startNode.getSecRole();
			Person startPerson = getStartPerson(roleName);
			String startId=startPerson.getId().toString();
			if (startPerson != null) {
				for (BpmAppInfo appInfo : list) {
					ProcessInstView processInstView = getProcessPvcService().startProcessInst(processConfigId, startPerson);
					String procinstId = processInstView.getProcessStatus().getProcinstId().toString();
					appInfo.setStartUser(startId);
					appInfo.setProcinstId(procinstId);
					appInfo.setAppTitle("本合同即将到期，请明确业务是否继续合作，落实合同续签事宜后回复");
					appInfo.setAppType("02");
					appInfo.setOpTime(new Date());
					getContractRemindDao().updateDue3MonthRemind(appInfo.getAppId(), "2");
					getContractRemindDao().merge(appInfo);
				}
			}
		}
		logger.info("合同3个月到期前提醒end>>>>");
	}

	public void runContractDue2MonthForBussOut() {
		logger.info("合同3个月到期前提醒start>>>>");
		List<BpmAppInfo> list = contractRemindDao.findDue3MonthContractList();
		if (list != null && list.size() > 0) {
			String processConfigId = getAppBusinessReqService().getFlowContractRemindProcessId();
			ProcessConfigDetail startNode = getProcessPvcService().getFlowPvcDao().getProcessStartNode(processConfigId);
			String roleName = startNode.getSecRole();
			Person startPerson = getStartPerson(roleName);
			String startId=startPerson.getId().toString();
			if (startPerson != null) {
				for (BpmAppInfo appInfo : list) {
					ProcessInstView processInstView = getProcessPvcService().startProcessInst(processConfigId, startPerson);
					String procinstId = processInstView.getProcessStatus().getProcinstId().toString();
					ContractBussout contractBussout=new ContractBussout();
					contractBussout.setUserId(startId);
					contractBussout.setReqCode(getAppBusinessReqService().getReqCode());		
					contractBussout.setApplyTime(new Date());
					contractBussout.setProcinstId(procinstId);
					contractBussout.setContractId(appInfo.getAppId());
					getContractRemindDao().merge(contractBussout);
					
					getContractRemindDao().updateDue3MonthRemind(appInfo.getAppId(), "2");
				}
			}
		}
		logger.info("合同3个月到期前提醒end>>>>");
	}	
	/**
	 * 强制结束流程
	 * 
	 * @param procInstId
	 */
	public void forceEndProcessInst(String procInstId) {

	}

	public void saveDataAndCommitTask(String flowTaskId, String content, List<TaskAssignBean> nextTasksList, String reDoUserIdArr[], boolean isCommit) {
		// 保存
		ProcTranRecord procTranRecord = null;
		if (isCommit) {
			procTranRecord = getTaskService().completeTask(flowTaskId, content, nextTasksList);
			// 将该任务传阅???
		} else {
			procTranRecord = getTaskService().saveTaskAssignUser(flowTaskId, content, nextTasksList);
		}
	}

	public void saveDataAndCommitTaskOfDeal(String flowTaskId, String content, List<TaskAssignBean> nextTasksList, boolean isCommit, ContractRemind contractRemind) {
		// 保存
		ProcTranRecord procTranRecord = null;
		if (isCommit) {
			procTranRecord = getTaskService().completeTask(flowTaskId, content, nextTasksList);
		} else {
			procTranRecord = getTaskService().saveTaskAssignUser(flowTaskId, content, nextTasksList);
		}
		if (contractRemind != null) {
			ContractRemind contractRemindForDb = getContractRemindDao().get(contractRemind.getId());
			contractRemindForDb.setCondNote(contractRemind.getCondNote());
			contractRemindForDb.setCondTime(contractRemind.getCondTime());
			getContractRemindDao().save(contractRemindForDb);
		}
	}

	public ProcTranRecord saveBussOutAndStartFlow(String processConfigId, Person person, List<TaskAssignBean> nextTasksList, boolean isCommit, ContractBussout contractBussout){
		ProcessInstView processInstView = getProcessPvcService().startProcessInst(processConfigId, person, nextTasksList, isCommit);
		contractBussout.setUserId(person.getId().toString());
		contractBussout.setReqCode(getAppBusinessReqService().getReqCode());		
		contractBussout.setApplyTime(new Date());
		contractBussout.setProcinstId(processInstView.getProcessStatus().getProcinstId().toString());
		getContractRemindDao().save(contractBussout);
		
		/**
		ContractInfo contractInfo = getContractRemindDao().getById(Integer.valueOf(contractBussout.getContractId()));
		
		BpmAppInfo appInfo=new BpmAppInfo();
		appInfo.setProcinstId(contractBussout.getProcinstId());
		appInfo.setAppTitle(contractInfo.getContractName()+"--业务退出");
		appInfo.setAppType("03");
		appInfo.setAppId(contractBussout.getContractId());
		appInfo.setOpTime(new Date());
		appInfo.setStartUser(contractBussout.getUserId());
		getContractRemindDao().save(appInfo);
		**/
		return processInstView.getProcTranRecord();
	}
			
	public void commitApplyTask(String flowTaskId,String content, List<TaskAssignBean> nextTasksList, boolean isCommit,ContractBussout contractBussout) throws Exception {
		// 保存
		//取时间
		getContractRemindDao().save(contractBussout);
		ProcTranRecord procTranRecord = null;
		if (isCommit) {
			procTranRecord = getTaskService().completeTask(flowTaskId, content, nextTasksList);
		} else {
			procTranRecord = getTaskService().saveTaskAssignUser(flowTaskId, content, nextTasksList);
		}
		//
	}
	
	
	public ContractRemindDao getContractRemindDao() {
		return contractRemindDao;
	}

	public void setContractRemindDao(ContractRemindDao contractRemindDao) {
		this.contractRemindDao = contractRemindDao;
	}

	public ProcessPvcService getProcessPvcService() {
		return processPvcService;
	}

	public void setProcessPvcService(ProcessPvcService processPvcService) {
		this.processPvcService = processPvcService;
	}

	public AppBusinessReqService getAppBusinessReqService() {
		return appBusinessReqService;
	}

	public void setAppBusinessReqService(AppBusinessReqService appBusinessReqService) {
		this.appBusinessReqService = appBusinessReqService;
	}

	public TaskService getTaskService() {
		return taskService;
	}

	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

	public ConfigBean getConfigBean() {
		return configBean;
	}

	public void setConfigBean(ConfigBean configBean) {
		this.configBean = configBean;
	}

}
